package com.bringspring.system.message.controller;


import com.alibaba.fastjson.JSONObject;
import com.bringspring.common.base.ActionResult;
import com.bringspring.common.base.Pagination;
import com.bringspring.common.base.UserInfo;
import com.bringspring.common.base.vo.PageListVO;
import com.bringspring.common.base.vo.PaginationVO;
import com.bringspring.common.constant.MsgCode;
import com.bringspring.common.exception.DataException;
import com.bringspring.common.model.login.BaseSystemInfo;
import com.bringspring.common.util.JsonUtil;
import com.bringspring.common.util.StringUtils;
import com.bringspring.common.util.UserProvider;
import com.bringspring.system.base.entity.MessageTemplateEntity;
import com.bringspring.system.base.entity.SysConfigEntity;
import com.bringspring.system.base.service.SysConfigService;
import com.bringspring.system.base.util.JsonUtilEx;
import com.bringspring.system.message.entity.MessageEntity;
import com.bringspring.system.message.entity.MessageReceiveEntity;
import com.bringspring.system.message.entity.SynThirdInfoEntity;
import com.bringspring.system.message.model.message.*;
import com.bringspring.system.message.service.MessageService;
import com.bringspring.system.message.service.SynThirdInfoService;
import com.bringspring.system.message.util.JsbosMessageUtil;
import com.bringspring.system.message.util.QyWebChatUtil;
import com.bringspring.system.message.util.SynThirdConsts;
import com.bringspring.system.permission.entity.UserEntity;
import com.bringspring.system.permission.entity.UserRelationEntity;
import com.bringspring.system.permission.service.UserRelationService;
import com.bringspring.system.permission.service.UserService;
import com.github.pagehelper.util.StringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.text.StringSubstitutor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 系统公告
 *
 * @author 开发平台组
 * @version V1.0.0
 * @copyright 股份有限公司
 * @date 2017年9月27日 上午9:18
 */
@Slf4j
@Api(tags = "系统公告", value = "Message")
@RestController
@RequestMapping("/api/message")
public class MessageController {

    @Autowired
    private MessageService messageService;
    @Autowired
    private UserService userService;
    @Autowired
    private UserRelationService userRelationService;
    @Autowired
    private SysConfigService sysConfigService;
    @Autowired
    private UserProvider userProvider;
    @Autowired
    private SynThirdInfoService synThirdInfoService;
    /**
     * 列表（通知公告）
     *
     * @param pagination
     * @return
     */
    @ApiOperation("获取系统公告列表（带分页）")
    @GetMapping("/Notice")
    public ActionResult<PageListVO<MessageNoticeVO>> noticeList(Pagination pagination) {
        List<MessageEntity> list = messageService.getNoticeList(pagination);
        List<UserEntity> userList = userService.getUserName(list.stream().map(t -> t.getCreatorUserId()).collect(Collectors.toList()));
        for (MessageEntity entity : list) {
            UserEntity user = userList.stream().filter(t -> t.getId().equals(entity.getCreatorUserId())).findFirst().orElse(null);
            entity.setCreatorUserId(user != null ? user.getRealName(): "");
        }
        PaginationVO paginationVO = JsonUtil.getJsonToBean(pagination, PaginationVO.class);
        List<MessageNoticeVO> voList = JsonUtil.getJsonToList(list, MessageNoticeVO.class);
        return ActionResult.page(voList, paginationVO);
    }

    /**
     * 添加系统公告
     *
     * @param noticeCrForm 实体对象
     * @return
     */
    @ApiOperation("添加系统公告")
    @PostMapping
    public ActionResult create(@RequestBody @Valid NoticeCrForm noticeCrForm) {
        MessageEntity entity = JsonUtil.getJsonToBean(noticeCrForm, MessageEntity.class);
        switch (entity.getSendType()) {
//           部门
            case "department":
                List<String> departmentList = Arrays.asList(entity.getSendId().split(","));
                List<String> userIds = userRelationService.getListByOrgId(departmentList).stream().map(UserRelationEntity::getUserId).collect(Collectors.toList());
                entity.setToUserIds(String.join(",",userIds));
        }

        messageService.create(entity);
        return ActionResult.success(MsgCode.SU001.get());
    }

    /**
     * 修改系统公告
     *
     * @param id            主键值
     * @param messageUpForm 实体对象
     * @return
     */
    @ApiOperation("修改系统公告")
    @PutMapping("/{id}")
    public ActionResult update(@PathVariable("id") String id, @RequestBody @Valid NoticeUpForm messageUpForm) {
        MessageEntity entity = JsonUtil.getJsonToBean(messageUpForm, MessageEntity.class);
        switch (entity.getSendType()) {
//           部门
            case "department":
                List<String> departmentList = Arrays.asList(entity.getSendId().split(","));
                List<String> userIds = userRelationService.getListByOrgId(departmentList).stream().map(UserRelationEntity::getUserId).collect(Collectors.toList());
                entity.setToUserIds(String.join(",",userIds));
        }
        boolean flag = messageService.update(id, entity);
        if (flag == false) {
            return ActionResult.fail(MsgCode.FA002.get());
        }
        return ActionResult.success(MsgCode.SU004.get());
    }

    /**
     * 信息
     *
     * @param id 主键值
     * @return
     */
    @ApiOperation("获取/查看系统公告信息")
    @GetMapping("/{id}")
    public ActionResult<NoticeInfoVO> info(@PathVariable("id") String id) throws DataException {
        MessageEntity entity = messageService.getinfo(id);
        UserEntity info = userService.getInfo(entity.getCreatorUserId());
        entity.setCreatorUserId(info != null ? info.getRealName(): "");
        NoticeInfoVO vo = JsonUtilEx.getJsonToBeanEx(entity, NoticeInfoVO.class);
        return ActionResult.success(vo);
    }

    /**
     * 删除
     *
     * @param id 主键值
     * @return
     */
    @ApiOperation("删除系统公告")
    @DeleteMapping("/{id}")
    public ActionResult delete(@PathVariable("id") String id) {
        MessageEntity entity = messageService.getinfo(id);
        if (entity != null) {
            messageService.delete(entity);
            return ActionResult.success(MsgCode.SU003.get());
        }
        return ActionResult.fail(MsgCode.FA003.get());
    }


    /**
     * 发布公告
     *
     * @param id 主键值
     * @return
     */
    @ApiOperation("发布系统公告")
    @Transactional
    @PutMapping("/{id}/Actions/Release")
    public ActionResult release(@PathVariable("id") String id) {
        MessageEntity entity = messageService.getinfo(id);
        if (entity != null) {
            List<String> userIds = null;
            switch (entity.getSendType()) {
                //用户
                case "user":
                    if (StringUtil.isNotEmpty(entity.getToUserIds())) {
                        userIds = Arrays.asList(entity.getToUserIds().split(","));
                    } else {
                        userIds = userService.getListId();
                    }
                    break;
                // 部门
                case "department":
                    userIds = Arrays.asList(entity.getToUserIds().replaceAll(" ","").split(","));
//                角色
//                case "role":
//                岗位
//                case "position":
            }
            messageService.sentNotice(userIds, entity);
            MessageTemplateEntity messageTemplateEntity = new MessageTemplateEntity();
            messageTemplateEntity.setTitle("发文：有新收到的公告等待您的阅读。");
            messageTemplateEntity.setContent("标题："+entity.getTitle());
            Map<String, String> map = new HashMap<>();
//            map.put("AppUrl", appPageConfig.getDomain() + "pages/notice/index?id="+entity.getId());
            //TODO
            map.put("AppUrl", "https://gl.bringspring.com/jsbos-app/#/pages/notice/index?id="+entity.getId());
            SendQyWebChat(userIds, userProvider.get(), "1", messageTemplateEntity, map);
            //如果调用消息模板使用下面代码，未完善，需修改。
//            String content=entity.getDescription()==null?"":entity.getDescription();
//            messageService.sendMessage(userIds, entity.getTitle(), content,entity.getId(),userProvider.get().getId());
//            entity.setEnabledMark(1);
//            messageService.updateById(entity);
            return ActionResult.success("发布成功");
        }
        return ActionResult.fail("发布失败");
    }
//=======================================站内消息、消息中心=================================================


    /**
     * 获取消息中心列表
     *
     * @param pagination
     * @return
     */
    @ApiOperation("列表（通知公告/系统消息/私信消息）")
    @GetMapping
    public ActionResult<PageListVO<MessageInfoVO>> messageList(PaginationMessage pagination) {
        List<MessageEntity> list = messageService.getMessageList(pagination, pagination.getType(),pagination.getAppid(), pagination.getIsShowRead());
        List<UserEntity> userList = userService.getUserName(list.stream().map(t -> t.getCreatorUserId()).collect(Collectors.toList()));
        for (MessageEntity entity : list) {
            UserEntity user = userList.stream().filter(t -> t.getId().equals(entity.getCreatorUserId())).findFirst().orElse(null);
            entity.setCreatorUserId(user != null ? user.getRealName() : "");
        }
        List<MessageInfoVO> listVO = JsonUtil.getJsonToList(list, MessageInfoVO.class);
        PaginationVO paginationVO = JsonUtil.getJsonToBean(pagination, PaginationVO.class);
        return ActionResult.page(listVO, paginationVO);
    }

    /**
     * 查看未读消息数
     *
     * @param userId
     * @return
     */
    @ApiOperation("列表（通知公告/系统消息/私信消息）")
    @PostMapping("/getUnreadCount")
    public ActionResult<Integer> getUnreadCount(String userId) {
        int unreadCount = messageService.getUnreadCount(userId);

        return ActionResult.success(unreadCount);
    }


    /**
     * 读取消息
     *
     * @param id 主键值
     * @return
     */
    @ApiOperation("读取消息")
    @GetMapping("/ReadInfo/{id}")
    public ActionResult readInfo(@PathVariable("id") String id) throws DataException {
        MessageEntity entity = messageService.getinfo(id);
        if (entity != null) {
            MessageReceiveEntity receive = messageService.messageRead(id);
            UserEntity user = userService.getInfo(entity.getCreatorUserId());
            entity.setCreatorUserId(user != null ? user.getRealName(): "");
            entity.setBodyText(receive != null ? receive.getBodyText() : null);
        }
        NoticeInfoVO vo = JsonUtilEx.getJsonToBeanEx(entity, NoticeInfoVO.class);
        return ActionResult.success(vo);
    }


    /**
     * 全部已读
     *
     * @return
     */
    @ApiOperation("全部已读")
    @PostMapping("/Actions/ReadAll")
    public ActionResult allRead() {
        messageService.messageRead();
        return ActionResult.success("已读成功");
    }

    /**
     * 删除记录
     *
     * @return
     */
    @ApiOperation("删除消息")
    @DeleteMapping("/Record")
    public ActionResult deleteRecord(@RequestBody MessageRecordForm recordForm) {
        String[] id = recordForm.getIds().split(",");
        List<String> list = Arrays.asList(id);
        messageService.deleteRecord(list);
        return ActionResult.success(MsgCode.SU003.get());
    }

    /**
     * 发送企业微信消息
     *
     * @param toUserIdsList
     * @param userInfo
     * @param sendType
     * @param entity
     * @param parameterMap
     * @return
     */
    private JSONObject SendQyWebChat(List<String> toUserIdsList, UserInfo userInfo, String sendType, MessageTemplateEntity entity, Map<String, String> parameterMap) {
        // 替换参数
        String content = entity.getContent();
        // 替换参数
        if (StringUtil.isNotEmpty(content) && null != parameterMap) {
            StringSubstitutor strSubstitutor = new StringSubstitutor(parameterMap, "{", "}");
            content = strSubstitutor.replace(content);
        }
        String title = entity.getTitle();
        // 替换参数
        if (StringUtil.isNotEmpty(title) && null != parameterMap) {
            StringSubstitutor strSubstitutor = new StringSubstitutor(parameterMap, "{", "}");
            title = strSubstitutor.replace(title);
        }
        // 获取系统配置
        Map<String, String> objModel = getSystemConfig();
        BaseSystemInfo config = JsonUtil.getJsonToBean(objModel, BaseSystemInfo.class);
        String corpId = config.getQyhCorpId();
        String agentId = config.getQyhAgentId();
        // 获取的应用的Secret值
        String corpSecret = config.getQyhAgentSecret();
        String wxUserId = "";
        StringBuilder toWxUserId = new StringBuilder();
        String toUserIdAll = "";
        StringBuilder nullUserInfo = new StringBuilder();
        List<MessageReceiveEntity> messageReceiveList = new ArrayList<>();
        JSONObject retJson = new JSONObject();

        // 相关参数验证
        if (StringUtil.isEmpty(corpId)) {
            log.error("企业ID为空");
        }
        if (StringUtil.isEmpty(corpSecret)) {
            retJson.put("code", false);
            retJson.put("error", "Secret为空");
            return retJson;
        }
        if (StringUtil.isEmpty(agentId)) {
            retJson.put("code", false);
            retJson.put("error", "AgentId为空");
            return retJson;
        }
        if (StringUtil.isEmpty(content)) {
            retJson.put("code", false);
            retJson.put("error", "内容为空");
            return retJson;
        }
        if (toUserIdsList == null || toUserIdsList.size() < 1) {
            retJson.put("code", false);
            retJson.put("error", "接收人为空");
            return retJson;
        }

        // 创建消息实体
        MessageEntity messageEntity = JsbosMessageUtil.setMessageEntity(userInfo.getUserId(), title, null, Integer.parseInt(sendType));

        // 获取接收人员的企业微信号、创建消息用户实体
        for (String userId : toUserIdsList) {
            wxUserId = "";
            // 从同步表获取对应的企业微信ID
            SynThirdInfoEntity synThirdInfoEntity = synThirdInfoService.getInfoBySysObjId(SynThirdConsts.THIRD_TYPE_QY, SynThirdConsts.DATA_TYPE_USER, userId);
            if (synThirdInfoEntity != null) {
                wxUserId = synThirdInfoEntity.getThirdObjectId();
            }
            if (StringUtil.isEmpty(wxUserId)) {
                nullUserInfo = nullUserInfo.append(",").append(userId);
            } else {
                toWxUserId = toWxUserId.append(",").append(wxUserId);
            }
            messageReceiveList.add(JsbosMessageUtil.setMessageReceiveEntity(messageEntity.getId(), userId));
        }

        // 处理企业微信号信息串并验证
        toUserIdAll = toWxUserId.toString();
        if (StringUtil.isNotEmpty(toUserIdAll)) {
            toUserIdAll = toUserIdAll.substring(1);
        }
        if (StringUtil.isEmpty(toUserIdAll)) {
            retJson.put("code", false);
            retJson.put("error", "接收人对应的企业微信号全部为空");
            return retJson;
        }
        String appUrl = parameterMap.get("AppUrl");
        // 批量发送企业信息信息
        retJson = QyWebChatUtil.sendWxMessage(corpId, corpSecret, agentId, toUserIdAll, title, content, appUrl);
        if (!retJson.getBoolean("code")) {
            return retJson;
        }

        // 企业微信号为空的信息写入备注
        if (StringUtil.isNotEmpty(nullUserInfo.toString())) {
            messageEntity.setDescription(nullUserInfo.substring(1) + "对应的企业微信号为空");
        }
        // 写入系统的消息表、消息用户表

        retJson.put("code", true);
        retJson.put("error", MsgCode.SU012.get());
        return retJson;
    }

    /**
     * 获取系统配置
     */
    private Map<String, String> getSystemConfig() {
        // 获取系统配置
        List<SysConfigEntity> configList = sysConfigService.getList();
        Map<String, String> objModel = new HashMap<>(16);
        for (SysConfigEntity entity : configList) {
            objModel.put(entity.getKeyName(), entity.getKeyValue());
        }
        return objModel;
    }
}
